//
//  HMUserAccountViewModel.swift
//  weibo
//
//  Created by LCH on 16/3/6.
//  Copyright © 2016年 lch. All rights reserved.
//

import UIKit

class HMUserAccountViewModel: NSObject {
    
    var userLogon: Bool {
    
        if self.accessToken != nil && !self.isExpiresIn{
        
         return true
        
        }
        return false
    }
    
    
    
    var accessToken: String? {
    
   
      return account?.access_token
    
    }
    
    
    
    var isExpiresIn: Bool {
    
        if NSDate().compare(account!.expires_date!) == .OrderedAscending {
        
          return false
        
        }else {
        
          return true
        }
    
    }
    
    
    var account:HMUserAccount?
    
    //TODO:为什么程序进来先执行单例的操作
    static let sharedAccountViewModel:HMUserAccountViewModel = {
    
      let vm = HMUserAccountViewModel()
        
      vm.account = vm.loadAccount()
        return vm
    
    }()
    
    // 这里闭包的定义和执行
     func loadAccessToken(code:String,callback:(isSuccess: Bool)->()) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let parameters = [
            "client_id": WB_appKey,
            "client_secret": WB_APPSECRET,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri":WB_REDIRECT_URI
            
        ]
        
        HMNetworkTools.sharedTools.requst(.POST, urlString: urlString, parameters: parameters) { (responseObject, error) -> () in
            
            if error != nil {
                
                print("\(error)")
                
                callback(isSuccess: false)
                return
                
            }
            print(responseObject)
            let account = HMUserAccount(dict:responseObject!)
            print(account)
            
            self.loadUserInfo(account,callback: callback)
        }
        
    }
    
    private func loadUserInfo(account:HMUserAccount,callback:(isSuccess: Bool)->()) {
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        guard let accessToken = account.access_token, uid = account.uid else{
            
            print("参数不够")
            callback(isSuccess: false)
            return
            
        }
        let parameters = [
            
            "access_token" : accessToken,
            "uid": uid
            
        ]
        
        HMNetworkTools.sharedTools.requst(.GET, urlString: urlString, parameters: parameters) { (responseObject, error) -> () in
            
            if error != nil {
                
                print("个人信息请求错误")
                callback(isSuccess: false)
//                SVProgressHUD.showErrorWithStatus("个人信息请求错误")
                return
                
            }
//            print(responseObject)
            
            account.screen_name = responseObject!["screen_name"] as? String
            account.avatar_large = responseObject!["avatar_large"] as? String
            
      
            
            self.saveUserAccount(account)
            
            self.account = account
            
            callback(isSuccess: true)
            
        }
        
        
        
    }

// 存档的文件名是否任意
    let file = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.archive")
    
    
    private func loadAccount() -> HMUserAccount? {
    
      return NSKeyedUnarchiver.unarchiveObjectWithFile(file) as? HMUserAccount
    
    
    }
    
    private func saveUserAccount(account:HMUserAccount) {
    
      
      NSKeyedArchiver.archiveRootObject(account, toFile: file)
    
    }
    

    

}
